//
//  PriceCarViewController.m
//  A段项目
//
//  Created by dlios on 15/7/25.
//  Copyright (c) 2015年 dlios. All rights reserved.
//

#import "PriceCarViewController.h"
#import "SANetWorkingTask.h"
#import "AllCarModel.h"
#import "recModel.h"
#import "SpecialCarModel.h"
#import "BaseHeader.h"
#import "SmallTableViewCell.h"
#import "CarRecTableViewCell.h"
#import "AllCarTableViewCell.h"
#import "smallTableModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SellRankDetailViewController.h"
#import "PriceViewController.h"

@interface PriceCarViewController ()<UITableViewDataSource, UITableViewDelegate>

@property  (nonatomic, retain) NSMutableArray *carArr;
@property  (nonatomic, retain)UITableView *bigTable;
@property  (nonatomic, retain) NSMutableArray *recArr;
@property  (nonatomic, retain) NSMutableArray *recSarr;
@property  (nonatomic, retain) UIView *listView;
@property  (nonatomic, retain) UITableView *smallTable;
@property  (nonatomic, retain) UIImageView *intro;
@property  (nonatomic, retain) NSMutableArray *section;
@property  (nonatomic, retain) NSMutableArray *smallArr;

@end

@implementation PriceCarViewController

- (void)dealloc
{
    [_carArr release];
    [_bigTable release];
    [_recArr release];
    [_recSarr release];
    [_listView release];
    [_smallTable release];
    [_intro release];
    [super dealloc];
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.recArr = [NSMutableArray array];
        self.carArr = [NSMutableArray array];
        self.recSarr = [NSMutableArray array];
        self.section = [NSMutableArray array];
        self.smallArr = [NSMutableArray array];
        
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择车款";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"w.png"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    // Do any additional setup after loading the view.
    
    [SANetWorkingTask request:@"http://api.ycapp.yiche.com/car/getmasterbrandlist?allmasterbrand=false " parmater:nil block:^(NSDictionary *result) {
        NSMutableArray *arr = [result objectForKey:@"data"];
        for (NSDictionary *dic in arr)
        {
            AllCarModel *carmodel = [[AllCarModel alloc] init];
            [carmodel setValuesForKeysWithDictionary:dic];
            [self.carArr addObject:carmodel];
            
            
        }
        [self makesection];
        
        [self.bigTable reloadData];
    }];
    
    [SANetWorkingTask request:@"http://api.ycapp.yiche.com/yicheapp/GetSelectCarPageAd?platform=2" parmater:nil block:^(NSDictionary *result) {
        
        NSDictionary *bigdic = [result objectForKey:@"data"];
        NSMutableArray *arr = [bigdic objectForKey:@"hotMaster"];
        NSMutableArray *arr1 = [bigdic objectForKey:@"hotSerial"];
        
        
        for (NSDictionary *dic in arr) {
            recModel *recmodel = [[recModel alloc] init];
            [recmodel setValuesForKeysWithDictionary:dic];
            [self.recArr addObject:recmodel];
        }
        for (NSDictionary *dic1  in arr1) {
            SpecialCarModel *carsmodel = [[SpecialCarModel alloc] init];
            [carsmodel setValuesForKeysWithDictionary:dic1];
            [self.recSarr addObject:carsmodel];
            
            
            
        }
        
        
        
        [self.bigTable reloadData];
        
    }];
    [self creatTable];
    
    
    self.listView = [[UIView alloc] initWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, ScreenHeidth)];
    _listView.layer.borderWidth = 1;
    [self.view addSubview:self.listView];
    self.listView.layer.borderColor = [[UIColor grayColor] CGColor];
    
    self.smallTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeidth-50) style:UITableViewStylePlain];
    self.smallTable.dataSource = self;
    self.smallTable.delegate = self;
    [self.smallTable registerClass:[SmallTableViewCell class] forCellReuseIdentifier:@"cc"];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 80)];
    self.intro = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 70, 60)];
    [self.intro setBackgroundColor:[UIColor whiteColor]];
    [view addSubview:self.intro];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(120, 30, 100, 20)];
    label.text = @"品牌介绍";
    label.font = [UIFont systemFontOfSize:18];
    [view addSubview:label];
    self.smallTable.tableHeaderView = view;
    
    [self.listView addSubview:self.smallTable];
    
    
}


#pragma mark 返回
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)creatTable
{
    self.bigTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeidth-50) style:UITableViewStylePlain];
    self.bigTable.delegate = self;
    self.bigTable.dataSource = self;
    
    [_bigTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"1"];
    [_bigTable registerClass:[AllCarTableViewCell class] forCellReuseIdentifier:@"bb"];
    [self.view addSubview:self.bigTable];
    
}

#pragma mark - 确定大taobleview的setion个数
- (void)makesection
{
    
    for (AllCarModel *model in self.carArr) {
        
        if (self.section.count == 0) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            NSMutableArray *array = [NSMutableArray array];
            [array addObject:model];
            [dic setValue:model.initial forKey:@"title"];
            [dic setValue:array forKey:@"array"];
            
            [self.section addObject:dic];
        }else{
            for (int i = 0; i<self.section.count; i++) {
                NSString *str = model.initial;
                if ([str isEqualToString:[[self.section lastObject]  objectForKey:@"title"]]) {
                    
                    
                    NSMutableArray *array = [[self.section lastObject] objectForKey:@"array"];
                    [array addObject:model];
                    
                    
                    
                }else{
                    
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    NSMutableArray *array=[NSMutableArray array];
                    [array addObject:model];
                    [dic setValue:model.initial forKey:@"title"];
                    [dic setValue:array forKey:@"array"];
                    [self.section addObject:dic];
                }
                break;
            }
        }
        
    }
    
    
}


#pragma mark - tableview两个协议
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.bigTable) {
        
        if (section == 0) {
            return 1;
        }else{
            NSDictionary *dic = [self.section objectAtIndex:section - 1] ;
            NSArray *arr = [dic objectForKey:@"array"];
            
            return arr.count;
        }
    }else
    {
        
        smallTableModel *model = [self.smallArr objectAtIndex:section];
        NSArray *arr = model.serialList;
        
        return arr.count;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    
    
    if (tableView == self.bigTable) {
        
        return self.section.count+1;
    } else {
        return self.smallArr.count;
    }
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.bigTable) {
        
        
        if (indexPath.section == 0) {
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = @"全部车型";

            
            return cell;
        }else{
            AllCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bb"];
            NSDictionary *dic = [self.section objectAtIndex:indexPath.section -1];
            NSArray *arr = [dic objectForKey:@"array"];
            AllCarModel *model = [arr objectAtIndex:indexPath.row];
            [cell.image sd_setImageWithURL:[NSURL URLWithString:model.logoUrl] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
            cell.nameLabel.text = model.name;
            
            
            
            return cell;
            
        }
    }
    else {
        SmallTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cc"];
        smallTableModel *model = [self.smallArr objectAtIndex:indexPath.section];
        NSArray *arr = model.serialList;
        NSDictionary *dic = [arr objectAtIndex:indexPath.row];
        NSString *str = [dic objectForKey:@"Picture"];
        if ([str containsString:@"{0}"]) {
            NSRange range = [str rangeOfString:@"{0}"];
            NSMutableString *str1 = [str mutableCopy];
            [str1 replaceCharactersInRange:range withString:@"3"];
            str = str1;
        }
        
        [cell.image sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        cell.nameLabel.text = [dic objectForKey:@"serialName"];
        
        if ([[dic objectForKey:@"dealerPrice"] isEqualToString:@"未上市"]) {
            cell.stateLabel.text = [dic objectForKey:@"dealerPrice"];
            cell.stateLabel.textColor = [UIColor grayColor];
            
        }else{
            cell.stateLabel.text = [dic objectForKey:@"dealerPrice"];
            cell.stateLabel.textColor = [UIColor redColor];
        }
        
        
        return cell;
    }
}







- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.bigTable) {
        
        if (indexPath.section == 0) {
            return 70;
        }else
        {
            return 70;
        }
    }else{
        return 90;
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.bigTable) {
        
        if (section == 0) {
            return nil;
        }else
        {
            NSDictionary *dic = [self.section objectAtIndex:section -1];
            return [dic objectForKey:@"title"];
        }
    }else{
        smallTableModel *model = [self.smallArr objectAtIndex:section];
        return model.brandName;
        
        
        
    }
    
    
}
#pragma mark - bigtableview的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.bigTable) {
        if (indexPath.section == 0) {
            [self.delegate sendStr:@"全部车型" serialid:nil];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            
            
            NSDictionary *dic1 = [self.section objectAtIndex:indexPath.section -1];
            NSArray *arr1 = [dic1 objectForKey:@"array"];
            AllCarModel *model1 = [arr1 objectAtIndex:indexPath.row];
            
            [self.intro sd_setImageWithURL:[NSURL URLWithString:model1.logoUrl] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
            
            __block PriceCarViewController *first = self;
            [UIView animateWithDuration:0.5 animations:^{
                first.listView.frame = CGRectMake(90, 0, ScreenWidth, ScreenHeidth);
                
            }];
            NSDictionary *dic = [self.section objectAtIndex:indexPath.section-1];
            NSArray *arr = [dic objectForKey:@"array"];
            AllCarModel *model = [arr objectAtIndex:indexPath.row];
            
            
            
            NSString *web = [NSString stringWithFormat:@"http://api.ycapp.yiche.com/car/getseriallist?masterid=%ld&allserial=false",model.masterId];
            
            [SANetWorkingTask request:web parmater:nil block:^(NSDictionary *result) {
                NSArray *arr = [result objectForKey:@"data"];
                self.smallArr = [NSMutableArray array];
                for (NSDictionary *dic in arr) {
                    smallTableModel *model = [[smallTableModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.smallArr addObject:model];
                }
                [self.smallTable reloadData];
            }];
        }
    }else
    {
        
        smallTableModel *model = [self.smallArr objectAtIndex:indexPath.section];
        NSArray *arr = model.serialList;
        NSDictionary *dic = [arr objectAtIndex:indexPath.row];
        [self.delegate sendStr:[dic objectForKey:@"serialName"] serialid:[dic objectForKey:@"serialId"]];
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    
}

#pragma mark - 添加索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.bigTable) {
        
        
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObject:@" "];
        for (NSDictionary *dic in self.section) {
            [arr addObject:[dic objectForKey:@"title"]];
            
        }
        return arr;
    }
    return nil;
    
    
}



#pragma mark - mark setion＝0里图片的点击事件
- (void)detailAction:(UITapGestureRecognizer *)tap
{
    if (tap.view.tag == 1) {
        SpecialCarModel *specialModel = [self.recSarr objectAtIndex:0];
        
        SellRankDetailViewController *rank = [[SellRankDetailViewController alloc] init];
        rank.website = specialModel.serialId;
        rank.name = specialModel.serialName;
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rank];
        
        
        [self presentViewController:nav animated:YES completion:nil];
    }if (tap.view.tag == 2) {
        SpecialCarModel *specialModel = [self.recSarr objectAtIndex:1];
        
        SellRankDetailViewController *rank = [[SellRankDetailViewController alloc] init];
        rank.website = specialModel.serialId;
        rank.name = specialModel.serialName;
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rank];
        
        
        [self presentViewController:nav animated:YES completion:nil];
        
    }if (tap.view.tag ==3) {
        SpecialCarModel *specialModel = [self.recSarr objectAtIndex:2];
        
        SellRankDetailViewController *rank = [[SellRankDetailViewController alloc] init];
        rank.website = specialModel.serialId;
        rank.name = specialModel.serialName;
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rank];
        
        
        [self presentViewController:nav animated:YES completion:nil];
        
    }
    
}

#pragma mark - tableview滑动时收起边栏
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    __block PriceCarViewController *first = self;
    if (scrollView == self.bigTable) {
        [UIView animateWithDuration:0.5 animations:^{
            first.listView.frame = CGRectMake(ScreenWidth, 0, ScreenWidth, ScreenHeidth);
            
        }];
    }
    
    
}

- (void)smallAction:(UITapGestureRecognizer *)tap
{
    
    recModel *model = [self.recArr objectAtIndex:tap.view.tag-1];
    [self.intro sd_setImageWithURL:[NSURL URLWithString:model.pic_url] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    
    [SANetWorkingTask request:[NSString stringWithFormat:@"http://api.ycapp.yiche.com/car/getseriallist?masterid=%ld&allserial=false",model.masterId] parmater:nil block:^(NSDictionary *result) {
        NSArray *arr = [result objectForKey:@"data"];
        self.smallArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            smallTableModel *model = [[smallTableModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.smallArr addObject:model];
        }
        [self.smallTable reloadData];
    }];
    
    
    __block PriceCarViewController *first = self;
    [UIView animateWithDuration:0.5 animations:^{
        first.listView.frame = CGRectMake(90, 0, ScreenWidth, ScreenHeidth);
        
    }];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
